package com.example.app.manager.giftplay

import androidx.core.view.isVisible
import androidx.lifecycle.LifecycleOwner
import androidx.multidex.BuildConfig
import com.blankj.utilcode.util.FileUtils
import com.blankj.utilcode.util.LogUtils
import com.libcommon.ext.workIO
import com.libhttp.HttpManager
import com.tencent.qgame.animplayer.AnimView
import com.tencent.qgame.animplayer.util.ALog
import com.tencent.qgame.animplayer.util.IALog
import com.tencent.qgame.animplayer.util.ScaleType
import java.io.File

/**
 * CreateBy:Joker
 * CreateTime:2024/9/10 18:02
 * description：
 */
object VapManager {
    const val TAG = "VapManager"

    fun init() {
        ALog.isDebug = BuildConfig.DEBUG
        ALog.log = object : IALog {
            override fun i(tag: String, msg: String) {
                //LogUtils.iTag(tag, msg)
            }

            override fun d(tag: String, msg: String) {
                //LogUtils.dTag(tag, msg)
            }

            override fun e(tag: String, msg: String) {
                LogUtils.eTag(tag, "VapManager,$msg")
            }

            override fun e(tag: String, msg: String, tr: Throwable) {
                LogUtils.eTag(tag, "VapManager$msg,${tr.message}")
            }
        }
    }

    /**
     * 本地文件播放
     */
    fun startPlay(animView: AnimView?, file: File, loop: Int = 1, playEnd: (() -> Unit)? = null) {
        animView?.let {
            it.setLoop(loop)
            // 居中（根据父布局按比例居中并全部显示，默认fitXY）
            it.setScaleType(ScaleType.FIT_CENTER)
            // 注册动画监听
            it.setAnimListener(object : VapCallBack() {
                override fun playEnd() {
                    playEnd?.invoke()
                }
            })
            it.isVisible = true
            workIO { it.startPlay(file) }
        }
    }

    /**
     * 在线播放
     */
    fun startPlayUrl(owner: LifecycleOwner, animView: AnimView?, url: String, targetPath: String, loop: Int = 1, playEnd: (() -> Unit)? = null) {
        HttpManager.downloadFile(owner, url, targetPath, reqResult = { code, _, msg ->
            LogUtils.dTag(TAG, "下载结果,code=$code,msg=$msg url=$url")
            if (code == HttpManager.CODE_SUCCESS) {
                startPlay(animView, FileUtils.getFileByPath(targetPath), loop, playEnd)
            } else {
                playEnd?.invoke()
            }
        })
    }

    fun stopPlay(animView: AnimView?) {
        animView?.let {
            it.setAnimListener(null)
            it.stopPlay()
        }
    }
}